/**
 * FileName: StructStreamingUtil
 * Author:   SAMSUNG-PC 孙中军
 * Date:     2018/12/13 11:15
 * Description: 使用的工具类
 */
package cn.com.bonc.util;

import cn.com.bonc.domain.UserInfo;
import com.alibaba.fastjson.JSONObject;
import org.apache.spark.sql.types.MetadataBuilder;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;

import java.util.Arrays;
import java.util.List;

import static org.apache.spark.sql.types.DataTypes.StringType;

public class StructStreamingUtil {

    /**
     * 获取一个UserInfo的StructType
     * @return
     */
    public static StructType getUsrStructType() {
        MetadataBuilder b = new MetadataBuilder();
        StructField[] fields = {
                new StructField("userName",StringType, true,b.build()),
                new StructField("certID",StringType, true,b.build()),
                new StructField("phoneID",StringType, true,b.build()),
                new StructField("unionID",StringType, true,b.build()),
                new StructField("mail",StringType, true,b.build()),
                new StructField("address",StringType, true,b.build()),
        };
        StructType type = new StructType(fields);
        return type;
    }


    /**
     * 测试使用的结构（临时可删除）
     * @return
     */
    public static StructType getAssociatedStructType() {
        MetadataBuilder b = new MetadataBuilder();
        StructField[] fields = {
                new StructField("userName",StringType, true,b.build()),
                new StructField("certID",StringType, true,b.build()),
        };
        StructType type = new StructType(fields);
        return type;
    }

    /**
     * 分割字符串并转换为Json串
     * @param str 被转换的字符串，并使用 “|”分割元素
     * @return
     */
    public static String parseValueToJsonStr(String str) {
        UserInfo userInfo =StructStreamingUtil.getUsrFromStr(str);
        String jsonStr = JSONObject.toJSONString(userInfo);
        return jsonStr;
    }

    /**
     * 对数据kafka格式进行过滤
     * 目前使用的数据格式为：
     * 漆雕滢|371523191105011680|山东济宁市金乡县王丕镇|18166541879|wowta63765@msn.com|6224228625456113315
     * @param str kafka数据
     * @return
     */
    public static boolean isStandardData(String str) {

        List<String> list = Arrays.asList(str.split("[|]"));
        if (list.size()==6){
            return true;
        }
        return false;
    }

    /**
     * 分割字符串并按照顺讯封装为UserInfo类
     * @param str
     * @return userInfo
     */
    public static UserInfo getUsrFromStr(String str) {
        List<String> list = Arrays.asList(str.split("[|]"));
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(list.get(0));
        userInfo.setCertID(list.get(1));
        userInfo.setAddress(list.get(2));
        userInfo.setPhoneID(list.get(3));
        userInfo.setMail(list.get(4));
        userInfo.setUnionID(list.get(5));
        return userInfo;
    }
}
